<template>
  <div id="app">
    <div class="table-container">
      <div class="buttons">
        <el-input v-model="goodsShelves" placeholder="请输入内容" style="width: 200px; margin-right: 10px;"></el-input>
        <el-button @click="handleQuery" style="background-color: #409eff; border-color: #409eff; color: #fff;">搜索</el-button>
        <el-button type="success" :disabled="selectedCells.length > 0 ? false:true" @click="mergeCells">合并单元格</el-button>
        <el-button type="danger" :disabled="selectedCells.length > 0 ? false:true" @click="splitCells">拆分单元格</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
      <div v-if="message" class="message">{{ message }}</div>
      <table>
        <thead>
          <tr>
            <th v-for="col in columns" :key="col">{{ col }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIndex) in rows" :key="rowIndex">
            <template v-for="(cell, colIndex) in row">
              <td
                :key="colIndex"
                v-if="cell.rowspan > 0 && cell.colspan > 0"
                :rowspan="cell.rowspan"
                :colspan="cell.colspan"
                @click="selectCell(rowIndex, colIndex)"
                :class="{ selected: isSelected(rowIndex, colIndex) }"
              >
                {{ cell.value }}
              </td>
            </template>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      goodsShelves:1,//货架
      columns: Array.from({ length: 24 }, (_, i) => `列 ${i + 1}`),
      rows: [],
      selectedCells: [],//选中的数组
      message: '',
    };
  },
  mounted() {
    this.init()
  },
  methods: {
    submit() {
      const result = [];

      this.rows.forEach((row, rowIndex) => {
        row.forEach((cell, colIndex) => {
          // 只处理有值的单元格
          if (cell.colspan > 0 && cell.value) {
            const portNo = cell.value; // 获取单元格的值
            const startIndex = colIndex + 1; // 转换为 1 基索引
            const endIndex = colIndex + cell.colspan; // 计算结束索引

            // 添加到结果数组
            result.push({
              portNo,
              startIndex,
              endIndex
            });

            // 跳过合并的单元格
            colIndex += cell.colspan - 1; // 跳过合并的单元格
          }
        });
      });

      // 输出结果
      console.log(result);
    },
    handleQuery(){
      //接口逻辑
      this.init()
    },
    init(){
      // 初始化表格
      let level = 6 //货架层数
      this.rows = Array.from({ length: level }, (item, i) =>
        Array.from({ length: 24 }, (jtem, j) => ({ value: `${i+1}-${j+1}`,rowspan: 1, colspan: 1 }))
      )
      this.selectedCells = []
      this.message = ''

      // 接收接口数据
      const data = [
        { "portNo": "1-1-01", "startIndex": 1, "endIndex": 6 },
        { "portNo": "1-1-02", "startIndex": 7, "endIndex": 7 },
        { "portNo": "1-2-02", "startIndex": 2, "endIndex": 6 },
        { "portNo": "1-3-02", "startIndex": 4, "endIndex": 6 },
        { "portNo": "1-4-02", "startIndex": 2, "endIndex": 16 },
        { "portNo": "1-5-01", "startIndex": 1, "endIndex": 3 },
        { "portNo": "1-5-02", "startIndex": 4, "endIndex": 5 },
        { "portNo": "1-5-03", "startIndex": 6, "endIndex": 6 },
      ];
      if(data.length > 0){
        // 填充数据
        data.forEach(item => {
          const { portNo, startIndex, endIndex } = item;
          const rowIndex = portNo.split('-')[1] - 1; // 取第二个元素; // 假设所有数据都在第一行，您可以根据需要调整行索引

          for (let colIndex = startIndex - 1; colIndex <= endIndex - 1; colIndex++) {
            if (colIndex === startIndex - 1) {
              // 第一个单元格，设置值和合并
              this.rows[rowIndex][colIndex].value = portNo;
              this.rows[rowIndex][colIndex].colspan =  endIndex - startIndex + 1;
            } else {
              // 其他单元格，设置为不可见
              this.rows[rowIndex][colIndex].colspan = 0;
            }
          }
        });
      }
      this.initRows()
      // 输出结果
      console.log(this.rows);
    },
    //从新排序
    initRows(){
      this.rows.forEach((item,i) => {
        if(item.length > 0){
          let jndex = 0
          item.forEach((jtem,j) => {
            if(jtem.colspan != 0){
              jtem.value = `${i+1}-${jndex+1}`
              jndex++
            }
          })
        }
      })
    },
    selectCell(rowIndex, colIndex) {
      const cell = this.rows[rowIndex][colIndex];

      const selectedIndex = this.selectedCells.findIndex(
        (cell) => cell.rowIndex === rowIndex && cell.colIndex === colIndex
      );

      if (selectedIndex === -1) {
        this.selectedCells.push({ rowIndex, colIndex });
      } else {
        this.selectedCells.splice(selectedIndex, 1);
      }

      // 按 colIndex 排序
      this.selectedCells.sort((a, b) => a.colIndex - b.colIndex);
      if(this.selectedCells.length == 0) this.message = '';//取消全部单元格，清空提示

      console.log('this.selectedCells',this.selectedCells)
    },
    isSelected(rowIndex, colIndex) {
      return this.selectedCells.some(
        (cell) => cell.rowIndex === rowIndex && cell.colIndex === colIndex
      );
    },
    // 选中合并的单元格,进行合并
    selectedCellsInit(){
      // 先检查所选单元格是否相邻
      const firstCell = this.selectedCells[0];
      const firstCellColspan = this.rows[firstCell.rowIndex][firstCell.colIndex];
      let startCol = Math.min(...this.selectedCells.map(cell => cell.colIndex));
      let colspanNum = firstCellColspan.colspan - 1
      const canMerge = this.selectedCells.every((cell, index) => {
        const cellColspan = this.rows[cell.rowIndex][cell.colIndex];
        if (index === 0) return true; // 第一个单元格
        if(firstCellColspan.colspan > 1){
          if(cellColspan.colspan > 1){
            if(cell.rowIndex === firstCell.rowIndex && cell.colIndex === firstCell.colIndex + colspanNum + index){
              return cell.rowIndex === firstCell.rowIndex && cell.colIndex === firstCell.colIndex + colspanNum + index,colspanNum += cellColspan.colspan - 1;
            }else{
              return false;
            }
          }
          return cell.rowIndex === firstCell.rowIndex && cell.colIndex === firstCell.colIndex + colspanNum + index;
        }else{
          return cell.rowIndex === firstCell.rowIndex && cell.colIndex === firstCell.colIndex + index;
        }
      });
      if (canMerge) {
        // 先拆分单个单元格
        let selectedCells = JSON.parse(JSON.stringify(this.selectedCells))
        this.selectedCells.forEach(({ rowIndex, colIndex }) => {
          const cell = this.rows[rowIndex][colIndex];
          if (cell.colspan > 1) {
            const originalValue = cell.value;
            const colspan = cell.colspan;
            for (let i = 0; i < colspan; i++) {
              this.rows[rowIndex][colIndex + i].rowspan = 1
              this.rows[rowIndex][colIndex + i].colspan = 1
              if(i != 0){
                selectedCells.push({
                  rowIndex:rowIndex,
                  colIndex:colIndex + i,
                })
              }
            }
            this.rows[rowIndex][colIndex].value = originalValue;
            this.rows[rowIndex][colIndex].colspan = 1;
          }
        });
        // 在合并成一个单元格
        const firstCellNew = selectedCells[0];
        let startColNew = Math.min(...selectedCells.map(cell => cell.colIndex));
        const endColNew = Math.max(...selectedCells.map(cell => cell.colIndex));
        const mergedCell = this.rows[firstCellNew.rowIndex][startColNew];
        mergedCell.colspan = endColNew - startColNew + 1;
        mergedCell.rowspan = 1; // 这里可以根据需要设置行数
        mergedCell.value = mergedCell.value || `合并 ${mergedCell.colspan} 列`;

        for (let i = startColNew; i <= endColNew; i++) {
          if (i !== startColNew) {
            this.rows[firstCellNew.rowIndex][i] = { value:this.rows[firstCellNew.rowIndex][i].value, rowspan: 1, colspan: 0 }; // 设置为0以避免显示
          }
        }
        this.selectedCells = [];
        this.message = ''; // 清空提示信息
      } else {
        this.message = '请选择相邻的单元格进行合并。';
      }
      this.initRows() //从新排序
    },
    // 合并单元格
    mergeCells() {
      if (this.selectedCells.length < 2) {
        this.message = '请至少选择两个单元格进行合并。';
        return;
      }

      // 检查所有选中的单元格是否在同一行
      const firstCell = this.selectedCells[0];
      for (const item of this.selectedCells) {
        if (item.rowIndex !== firstCell.rowIndex) {
          this.message = '只能合并同一行的单元格。';
          return; // 只能合并同一行
        }
      }

      // 合并的单元格需要先拆分,在操作合并。
      for (const item of this.selectedCells) {
        const cell = this.rows[item.rowIndex][item.colIndex];
        if (cell.colspan > 1) {
            // this.message = '合并的单元格需要先拆分,在操作合并。';
            this.selectedCellsInit() // 选中合并的单元格,进行合并
            return;
          }
      }

      let startCol = Math.min(...this.selectedCells.map(cell => cell.colIndex));
      const endCol = Math.max(...this.selectedCells.map(cell => cell.colIndex));
      // console.log('startCol',startCol)
      // console.log('endCol',endCol)
      // 检查所选单元格是否相邻
      const canMerge = this.selectedCells.every((cell, index) => {
        if (index === 0) return true; // 第一个单元格
        return cell.rowIndex === firstCell.rowIndex && cell.colIndex === startCol + index;
      });

      if (canMerge) {
        const mergedCell = this.rows[firstCell.rowIndex][startCol];
        mergedCell.colspan = endCol - startCol + 1;
        mergedCell.rowspan = 1; // 这里可以根据需要设置行数
        mergedCell.value = mergedCell.value || `合并 ${mergedCell.colspan} 列`;

        for (let i = startCol; i <= endCol; i++) {
          if (i !== startCol) {
            this.rows[firstCell.rowIndex][i] = { value:this.rows[firstCell.rowIndex][i].value, rowspan: 1, colspan: 0 }; // 设置为0以避免显示
          }
        }
        this.selectedCells = [];
        this.message = ''; // 清空提示信息
        // console.log('this.rows',this.rows)
      } else {
        this.message = '请选择相邻的单元格进行合并。';
      }
      this.initRows() //从新排序
    },
    // 拆分单元格
    splitCells() {
      this.selectedCells.forEach(({ rowIndex, colIndex }) => {
        const cell = this.rows[rowIndex][colIndex];
        if (cell.colspan > 1) {
          const originalValue = cell.value;
          const colspan = cell.colspan;

          for (let i = 0; i < colspan; i++) {
            this.rows[rowIndex][colIndex + i].rowspan = 1
            this.rows[rowIndex][colIndex + i].colspan = 1
          }

          this.rows[rowIndex][colIndex].value = originalValue;
          this.rows[rowIndex][colIndex].colspan = 1;
        }
      });
      this.selectedCells = [];
      this.message = ''; // 清空提示信息
      this.initRows()
    },
  },
};
</script>

<style>
.table-container {
  margin: 20px;
  overflow-x: scroll;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid black;
  padding: 10px;
  text-align: center;
  cursor: pointer;
}

.selected {
  background-color: #cce5ff;
}

.buttons {
  margin-top: 10px;
  margin-bottom: 10px;
}

button {
  margin-right: 10px;
  padding: 5px 10px;
}

.message {
  color: red;
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
